package com.xxx.control

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.AppUtils.isAppRunning
import com.xxx.control.activity.HomeActivity
import com.xxx.control.base.BaseVMActivity
import com.xxx.control.base.ext.clickWithTrigger
import com.xxx.control.databinding.ActivityMainBinding
import com.xxx.control.viewmodel.TestViewModel


class MainActivity : BaseVMActivity<ActivityMainBinding, TestViewModel>() {

    private val TARGET_PACKAGE_NAME = "com.embedded.nativeapp" // 目标应用程序的包名

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        mBinding.text.text = ""
//
//
//        mViewModel.testString.observe(this) {
//            mBinding.text.text = it
//        }
//
//        mBinding.button.clickWithTrigger {
//            AppUtils.exitApp()
//        }

        startActivity(HomeActivity::class.java)
        return
//        AppUtils.launchApp(TARGET_PACKAGE_NAME)


//        mBinding.imageView.loadImage("https://www.baidu.com/img/bd_logo1.png?where=super")

//        startTargetApp()
    }

    private fun startTargetApp() {
        val isAppRunning = isAppRunning(this, TARGET_PACKAGE_NAME)
        if (isAppRunning) {
            // 如果目标应用程序已经在运行，则重新启动它
            val intent = packageManager.getLaunchIntentForPackage(TARGET_PACKAGE_NAME)
            if (intent != null) {
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                startActivity(intent)
            }
        } else {
            // 如果目标应用程序未在运行，则启动它
            val intent = Intent(Intent.ACTION_MAIN)
            intent.addCategory(Intent.CATEGORY_LAUNCHER)
            intent.setComponent(
                ComponentName(
                    TARGET_PACKAGE_NAME,
                    "$TARGET_PACKAGE_NAME.MainActivity"
                )
            )
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
        }
        finish() // 结束当前的Activity，使启动过程更加静默
    }

    private fun isAppRunning(context: Context, packageName: String): Boolean {
        val pm = context.packageManager
        val intent = pm.getLaunchIntentForPackage(packageName)
        return intent != null
    }

}